#!/bin/bash

# 检查参数数量
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <commit_hashes_and_times.txt>"
    exit 1
fi

# 参数
INPUT_FILE=$1
GIT_FILTER_REPO_PATH="./git_filter_repo.py"

# 验证 git-filter-repo 是否存在
if [ ! -f "$GIT_FILTER_REPO_PATH" ]; then
    echo "Error: git-filter-repo not found at $GIT_FILTER_REPO_PATH"
    exit 1
fi

# 遍历输入文件逐行处理
while IFS=',' read -r commit_hash commit_time timestamp; do
    # 转换时间为 UNIX 时间戳
    unix_timestamp=$(date -d "$timestamp" +%s)
    formatted_time="${unix_timestamp} +0800"

    echo "Modifying commit $commit_hash with timestamp $timestamp ($formatted_time)"

    # 执行 git-filter-repo
    # --refs test..master 指定要处理的分支范围
    # --refs test..HEAD
    # --refs HEAD~2..master
    python3 "$GIT_FILTER_REPO_PATH" --commit-callback "
    committer_date_bytes = commit.committer_date
    committer_date_str = committer_date_bytes.decode('utf-8')
    committer_timestamp = int(committer_date_str.split(' ')[0])
    if committer_timestamp == $commit_time:
        commit.author_date = b'$formatted_time'
        commit.committer_date = b'$formatted_time'
    "

    # 检查执行结果
    if [ $? -eq 0 ]; then
        echo "Successfully modified commit $commit_hash"
    else
        echo "Error occurred while modifying commit $commit_hash"
        exit 1
    fi
done < "$INPUT_FILE"

echo "All commits have been modified."

# 批量修改时间戳
# sh modifyTimes.sh commit_hashes_and_times.csv
